package com.atguigu.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.CaseFormat;
import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @className: JdbcUtil
 * @author: LinCong
 * @description:    希望当前工具类可以适用于任何JDBC方式访问的数据库中的任何查询语句
 * @date: 2023/2/14 12:47
 * @version: 1.0
 */
public class JdbcUtil {
//    underScoreToCamel 下划线转驼峰  Class<T>    传入返回类的类型（为了构造返回类对象实例）
    public static <T> List<T> queryList(Connection connection,String sql,Class<T> clz,boolean underScoreToCamel) throws SQLException, IllegalAccessException, InstantiationException, InvocationTargetException {
//        创建集合用于存放结果数据
        ArrayList<T> result = new ArrayList<>();

//        编译SQL语句
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

//        执行查询
        ResultSet resultSet = preparedStatement.executeQuery();

//        获取查询的元数据信息
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();

//        遍历结果集，将每行数据转换为T对象并加入集合
        while (resultSet.next()){
//            创建T对象
            T t = clz.newInstance();
//            列遍历
            for (int i=0;i<columnCount;i++){
//                获取列名与列值
                String culumnName = metaData.getColumnName(i+1);
                Object value = resultSet.getObject(culumnName);
//                判断是否需要进行下划线与驼峰命名转换
                if (underScoreToCamel){
//                    "lower_underscore"    --->    "lowerCamel"
                    culumnName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, culumnName.toLowerCase());
                }

//                赋值
                BeanUtils.setProperty(t,culumnName,value);
            }

//            将T对象放入集合
            result.add(t);
        }

        preparedStatement.close();
        resultSet.close();

//        返回集合
        return result;
    }


    public static void main(String[] args) throws SQLException, IllegalAccessException, InvocationTargetException, InstantiationException {
        DruidDataSource dataSource = DruidDSUtil.createDataSource();
        DruidPooledConnection connection = dataSource.getConnection();

        List<JSONObject> jsonObjects = queryList(connection, "select * from GMALL_REALTIME.DIM_BASE_TRADEMARK ", JSONObject.class, true);
        System.out.println(jsonObjects);
        System.out.println("===============");
        for (JSONObject jsonObject : jsonObjects) {
            System.out.println(jsonObject);
        }

        connection.close();
    }
}
